#include<stdio.h>
#include<stdlib.h>

typedef struct employee{
	int name_length;
	char *name;
	float salary;
} Employee;

Employee **build_arr(FILE *fp, int *size)
{
	int physize = 2, flag;
	Employee *ret;
	Employee **res;
	*size = 0;
	ret = malloc(sizeof(Employee) * physize);
	while(1)
	{
		if(*size>=physize)
		{
			physize*=2;
			ret = realloc(ret, sizeof(Employee) * physize);
		}
		flag = fread(&ret[*size].name_length, sizeof(int), 1, fp);
		if(!flag) break;
		ret[*size].name = malloc(sizeof(char) * ret[*size].name_length);
		fread(ret[*size].name, sizeof(char), ret[*size].name_length, fp);
		fread(&(ret[*size].salary), sizeof(float), 1, fp);
		(*size)++;


	}
	ret = realloc(ret, sizeof(Employee) * (*size));
	res = malloc(sizeof(Employee **) * (*size));
	for(int i=0;i<(*size);i++)
		res[i] = ret + i;
	return res;

}

float *build_salary(FILE *fp, int size)
{
	float *ret;
	ret = malloc(sizeof(float) * size);
	fread(ret, sizeof(float), size, fp);
	return ret;
}

void update_salaries(Employee **emps, float *salaries, int size)
{
	for(int i=0;i<size;i++)
		emps[i]->salary+=salaries[i];
}

void employee_sort(Employee **arr, int size)
{
	Employee *temp;
	for(int i=0;i<size;i++)
		for(int j=0;j<i;j++)
			if(arr[j]->salary<arr[j+1]->salary)
			{
				temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
			}
}

void employee_write(Employee **arr, int size, FILE *fp)
{
	for(int i=0;i<size;i++)
	{
		fwrite(arr[i],sizeof(Employee), 1, fp);
	}
}

int main(int argc, char *argv[])
{
	Employee **arr;
	float *salaries;
	FILE *fp;
	int size;
	if(argc< 3)
	{
		printf("usage: %s <filename1> <filename2>", argv[0]);
		return 1;
	}
	fp = fopen(argv[1], "rb");
	arr = build_arr(fp, &size);
	fclose(fp);
	fp = fopen(argv[2], "rb");
	salaries = build_salary(fp, size);
	update_salaries(arr, salaries, size);
	free(salaries);
	employee_sort(arr, size);
	fclose(fp);
	fopen(argv[1], "wb");
	employee_write(arr, size, fp);
	//DEBUG:
	for(int i=0;i<size;i++)
		printf("%d: %s, %f\n", arr[i]->name_length, arr[i]->name, arr[i]->salary);
	for(int i=0;i<size;i++)
		printf("%f\n", salaries[i]);
	//END OF DEBUG
	free(arr);
	fclose(fp);
	return 0;
}
